package com.lineage.data.npc.shop;

import com.lineage.data.cmd.CreateNewItem;
import com.lineage.data.event.ShopXSet;
import com.lineage.data.executor.NpcExecutor;
import com.lineage.server.datatables.ItemRestrictionsTable;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.ShopXTable;
import com.lineage.server.datatables.lock.CharItemPowerReading;
import com.lineage.server.datatables.lock.DwarfShopReading;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_CloseList;
import com.lineage.server.serverpackets.S_CnSRetrieve;
import com.lineage.server.serverpackets.S_CnSShopSellList;
import com.lineage.server.serverpackets.S_CnSShopSellListarmor;
import com.lineage.server.serverpackets.S_NPCTalkReturn;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1ShopS;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Npc_ShopX2 extends NpcExecutor {
  private static final Log _log = LogFactory.getLog(Npc_ShopX2.class);
  
  private static final int _count = 200;
  
  public static int _itemid = 0;
  
  public static NpcExecutor get() {
    return new Npc_ShopX2();
  }
  
  public int type() {
    return 3;
  }
  
  public void talk(L1PcInstance pc, L1NpcInstance npc) {
    try {
      pc.get_other().set_item_objid(0);
      String[] info = { String.valueOf(ShopXSet.ADENA), String.valueOf(ShopXSet.DATE), 
          String.valueOf(ShopXSet.MIN), String.valueOf(ShopXSet.MAX) };
      pc.sendPackets((ServerBasePacket)new S_NPCTalkReturn(npc.getId(), "y_x_1", info));
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public void action(L1PcInstance pc, L1NpcInstance npc, String cmd, long amount) {
    if (cmd.equalsIgnoreCase("s")) {
      cmd_s2(pc, npc);
    } else if (cmd.equalsIgnoreCase("i")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellList(pc, npc));
    } else if (cmd.equalsIgnoreCase("shopweapon")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellList(pc, npc));
    } else if (cmd.equalsIgnoreCase("shoparmor2")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 2));
    } else if (cmd.equalsIgnoreCase("shoparmor18")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 18));
    } else if (cmd.equalsIgnoreCase("shoparmor19")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 19));
    } else if (cmd.equalsIgnoreCase("shoparmor20")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 20));
    } else if (cmd.equalsIgnoreCase("shoparmor21")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 21));
    } else if (cmd.equalsIgnoreCase("shoparmor22")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 22));
    } else if (cmd.equalsIgnoreCase("shoparmor23")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 23));
    } else if (cmd.equalsIgnoreCase("shoparmor24")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 24));
    } else if (cmd.equalsIgnoreCase("shoparmor25")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 25));
    } else if (cmd.equalsIgnoreCase("shoparmor40")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 40));
    } else if (cmd.equalsIgnoreCase("shoparmor37")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 37));
    } else if (cmd.equalsIgnoreCase("shoparmorother")) {
      pc.sendPackets((ServerBasePacket)new S_CnSShopSellListarmor(pc, npc, 50));
    } else if (cmd.equalsIgnoreCase("l")) {
      cmd_1(pc, npc);
    } else if (cmd.equalsIgnoreCase("ma")) {
      cmd_ma(pc, npc, amount);
    } else if (cmd.equals("up")) {
      int page = pc.get_other().get_page() - 1;
      showPage(pc, npc.getId(), page);
    } else if (cmd.equals("dn")) {
      int page = pc.get_other().get_page() + 1;
      showPage(pc, npc.getId(), page);
    } else if (cmd.equals("over")) {
      cmd_over(pc, npc);
    } else if (cmd.equals("no")) {
      pc.setTempID(0);
      pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
    } else if (cmd.matches("[0-9]+")) {
      String pagecmd = String.valueOf(String.valueOf(pc.get_other().get_page())) + cmd;
      update(pc, npc, Integer.parseInt(pagecmd));
    } 
  }
  
  public static void cmd_1(L1PcInstance pc, L1NpcInstance npc) {
    try {
      (pc.get_otherList()).SHOPXMAP.clear();
      Map<Integer, L1ShopS> temp = DwarfShopReading.get().getShopSMap(pc.getId());
      if (temp != null) {
        (pc.get_otherList()).SHOPXMAP.putAll(temp);
        temp.clear();
      } 
      showPage(pc, npc.getId(), 0);
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public static void cmd_ma(L1PcInstance pc, L1NpcInstance npc, long amount) {
    try {
      int objid = pc.get_other().get_item_objid();
      L1ItemInstance itemT = pc.getInventory().checkItemX(_itemid, ShopXSet.ADENA);
      boolean isError = false;
      if (objid == 0)
        isError = true; 
      if (itemT == null) {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(337, ItemTable.get().getTemplate(_itemid).getName()));
        isError = true;
      } 
      if (amount < ShopXSet.MIN)
        isError = true; 
      if (amount > ShopXSet.MAX)
        isError = true; 
      if (isError) {
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        pc.get_other().set_item_objid(0);
        return;
      } 
      L1ItemInstance item = pc.getInventory().getItem(objid);
      if (item == null) {
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        return;
      } 
      if (item.isEquipped())
        isError = true; 
      if (!item.isIdentified())
        isError = true; 
      if (item.getItem().getMaxUseTime() != 0)
        isError = true; 
      if (ShopXTable.get().getTemplate(item.getItem().getItemId()) != null)
        isError = true; 
      if (item.getEnchantLevel() < 0)
        isError = true; 
      if (item.getItem().getMaxChargeCount() != 0 && item.getChargeCount() <= 0)
        isError = true; 
      if (isError) {
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        pc.get_other().set_item_objid(0);
        return;
      } 
      pc.get_other().set_item_objid(0);
      long time = (ShopXSet.DATE * 24 * 60 * 60 * 1000);
      Timestamp overTime = new Timestamp(System.currentTimeMillis() + time);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String key = sdf.format(overTime);
      String[] info = { item.getLogName(), String.valueOf(amount), key };
      pc.sendPackets((ServerBasePacket)new S_NPCTalkReturn(npc.getId(), "y_x_4", info));
      L1ShopS shopS = new L1ShopS();
      shopS.set_id(DwarfShopReading.get().nextId());
      shopS.set_item_obj_id(item.getId());
      shopS.set_user_obj_id(pc.getId());
      shopS.set_adena((int)amount);
      shopS.set_overtime(overTime);
      shopS.set_end(0);
      String outname = item.getNumberedName_to_String();
      shopS.set_none(outname);
      shopS.set_item(item);
      pc.getInventory().removeItem(itemT, ShopXSet.ADENA);
      pc.getInventory().removeItem(item);
      DwarfShopReading.get().insertItem(item.getId(), item, shopS);
      try {
        pc.save();
        pc.saveInventory();
      } catch (Exception e) {
        _log.error(e.getLocalizedMessage(), e);
      } 
    } catch (Exception e2) {
      _log.error(e2.getLocalizedMessage(), e2);
    } 
  }
  
  public static void cmd_over(L1PcInstance pc, L1NpcInstance npc) {
    try {
      L1ShopS shopS = DwarfShopReading.get().getShopS(pc.getTempID());
      pc.setTempID(0);
      shopS.set_end(3);
      shopS.set_item(null);
      DwarfShopReading.get().updateShopS(shopS);
      pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  private static void cmd_s1(L1PcInstance pc, L1NpcInstance npc) {
    try {
      Map<Integer, L1ShopS> allShopS = DwarfShopReading.get().allShopS();
      if (allShopS.size() >= 200) {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(75));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        return;
      } 
      L1ItemInstance itemT = pc.getInventory().checkItemX(_itemid, ShopXSet.ADENA);
      if (itemT == null) {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(337, ItemTable.get().getTemplate(_itemid).getName()));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        return;
      } 
      List<L1ItemInstance> itemsx = new CopyOnWriteArrayList<>();
      List<L1ItemInstance> items = pc.getInventory().getItems();
      for (L1ItemInstance item : items) {
        if (ShopXTable.get().getTemplate(item.getItem().getItemId()) != null)
          continue; 
        if (item.isEquipped())
          continue; 
        if (!item.isIdentified())
          continue; 
        if (item.getItem().getMaxUseTime() != 0)
          continue; 
        if (item.get_time() != null)
          continue; 
        if (item.getEnchantLevel() < 0)
          continue; 
        if (item.getItem().getMaxChargeCount() != 0 && item.getChargeCount() <= 0)
          continue; 
        if (ItemRestrictionsTable.RESTRICTIONS.contains(Integer.valueOf(item.getItemId())))
          continue; 
        itemsx.add(item);
      } 
      pc.sendPackets((ServerBasePacket)new S_CnSRetrieve(pc, npc.getId(), itemsx));
      allShopS.clear();
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public static void cmd_s2(L1PcInstance pc, L1NpcInstance npc) {
    try {
      Map<Integer, L1ShopS> allShopS = DwarfShopReading.get().allShopS();
      if (allShopS.size() >= 200) {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(75));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        return;
      } 
      L1ItemInstance itemT = pc.getInventory().checkItemX(_itemid, ShopXSet.ADENA);
      if (itemT == null) {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(337, ItemTable.get().getTemplate(_itemid).getName()));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        return;
      } 
      List<L1ItemInstance> itemsx = new CopyOnWriteArrayList<>();
      List<L1ItemInstance> items = pc.getInventory().getItems();
      Iterator<L1ItemInstance> iterator = items.iterator();
      while (iterator.hasNext()) {
        L1ItemInstance item = iterator.next();
        if (ShopXTable.get().getTemplate(item.getItem().getItemId()) != null)
          continue; 
        if (!item.getItem().isTradable())
          continue; 
        if (item.isEquipped())
          continue; 
        if (!item.isIdentified())
          continue; 
        if (item.getItem().getMaxUseTime() != 0)
          continue; 
        if (item.get_time() != null)
          continue; 
        if (item.getEnchantLevel() < 0)
          continue; 
        if (item.getItem().getMaxChargeCount() != 0 && item.getChargeCount() <= 0)
          continue; 
        if (ItemRestrictionsTable.RESTRICTIONS.contains(Integer.valueOf(item.getItemId())))
          continue; 
        itemsx.add(item);
      } 
      pc.sendPackets((ServerBasePacket)new S_CnSRetrieve(pc, npc.getId(), itemsx));
      allShopS.clear();
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public static void update(L1PcInstance pc, L1NpcInstance npc, int key) {
    SimpleDateFormat sdf;
    L1ItemInstance item;
    String overTime, info[];
    Map<Integer, L1ShopS> list = (pc.get_otherList()).SHOPXMAP;
    pc.setTempID(0);
    L1ShopS shopS = list.get(Integer.valueOf(key));
    switch (shopS.get_end()) {
      case 0:
        pc.setTempID(shopS.get_item_obj_id());
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        overTime = sdf.format(shopS.get_overtime());
        info = new String[] { String.valueOf(String.valueOf(shopS.get_item().getLogName())) + "(" + shopS.get_item().getCount() + ")", 
            String.valueOf(shopS.get_adena()), overTime };
        pc.sendPackets((ServerBasePacket)new S_NPCTalkReturn(npc.getId(), "y_x_5", info));
        break;
      case 1:
        shopS.set_end(2);
        DwarfShopReading.get().updateShopS(shopS);
        CreateNewItem.createNewItem(pc, _itemid, shopS.get_adena());
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        break;
      case 2:
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, "该托售物品收入已领回"));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        break;
      case 3:
        shopS.set_end(4);
        shopS.set_item(null);
        DwarfShopReading.get().updateShopS(shopS);
        item = (L1ItemInstance)DwarfShopReading.get().allItems().get(Integer.valueOf(shopS.get_item_obj_id()));
        DwarfShopReading.get().deleteItem(shopS.get_item_obj_id());
        pc.getInventory().storeTradeItem(item);
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(403, item.getLogName()));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        break;
      case 4:
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, "该托售物品已领回"));
        pc.sendPackets((ServerBasePacket)new S_CloseList(pc.getId()));
        break;
    } 
    CharItemPowerReading.get().load();
    pc.get_other().set_item_objid(0);
  }
  
  public static void showPage(L1PcInstance pc, int npcobjid, int page) {
    Map<Integer, L1ShopS> list = (pc.get_otherList()).SHOPXMAP;
    if (list == null)
      return; 
    int allpage = list.size() / 10;
    if (page > allpage || page < 0)
      page = 0; 
    if (list.size() % 10 != 0)
      allpage++; 
    pc.get_other().set_page(page);
    int or = page * 10;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(String.valueOf(String.valueOf(page + 1)) + "/" + allpage + ",");
    int key = or;
    while (key < or + 10) {
      L1ShopS shopS = list.get(Integer.valueOf(key));
      if (shopS != null) {
        stringBuilder.append(String.valueOf(String.valueOf(shopS.get_none())) + " / " + shopS.get_adena() + ",");
        switch (shopS.get_end()) {
          case 0:
            stringBuilder.append("出售中,");
            break;
          case 1:
            stringBuilder.append("已售出未领回,");
            break;
          case 2:
            stringBuilder.append("已售出已领回,");
            break;
          case 3:
            stringBuilder.append("未售出未领回,");
            break;
          case 4:
            stringBuilder.append("未售出已领回,");
            break;
        } 
      } else {
        stringBuilder.append(" ,");
      } 
      key++;
    } 
    if (allpage >= page + 1) {
      String out = stringBuilder.toString();
      String[] clientStrAry = out.split(",");
      pc.sendPackets((ServerBasePacket)new S_NPCTalkReturn(npcobjid, "y_x_2", clientStrAry));
    } else {
      pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, "没有可以显示的项目"));
    } 
  }
  
  public void set_set(String[] set) {
    try {
      _itemid = Integer.parseInt(set[1]);
    } catch (Exception e) {
      _log.error("NPC专属货币设置错误:检查CLASSNAME为Npc_Strange的NPC设置!");
    } 
  }
}
